<template>
  <div class="clothes-info">
    <div class="clothes-image">
      <img src="https://picsum.photos/200/200" alt="商品图片" class="goods-img">
    </div>
    <div class="clothes-info-content">
      <div class="clothes-info-content-text">
        <h1 class="goods-name">{{ clothes.clothesName  }}</h1>
        <p class="goods-desc">{{ clothes.description  }}</p>
        <p class="goods-price">¥{{ clothes.price}}/天</p>
      </div>

      <!-- 尺寸选择区 -->
      <div class="clothes-size-selector">
        <h3 class="size-title">选择尺寸</h3>
        <div class="size-radio-group">
          <label class="size-radio" v-for="size in sizeOptions" :key="size.size">
            <input 
              type="radio" 
              name="clothesSize" 
              v-model="selectedSize" 
              :value="size.size" 
              :disabled="!size.totalNum"
              class="native-radio"
            >
            <span class="radio-btn">
              {{ size.size }}
              <span class="stock-tip" v-if="!size.totalNum">无货</span>
            </span>
          </label>
          <!-- 自定义尺寸输入框 -->
          <input 
            type="text" 
            placeholder="自定义尺寸" 
            v-model="selectedSize" 
            class="size-input"
            @input="handleCustomSize"
          >
        </div>
      </div>

      <!-- 日期选择区 -->
      <div class="clothes-rent-date-selector">
        <h3 class="date-title">租借时间</h3>
        <div class="date-group">
          <input 
            type="date" 
            placeholder="租借开始日" 
            v-model="selectedDate" 
            class="date-input"
            :min="getToday()"
          >
          <span class="date-gap">至</span>
          <input 
            type="date" 
            placeholder="租借归还日" 
            v-model="returnDate" 
            class="date-input"
            :min="selectedDate || getToday()"
          >
        </div>
        <!-- 日期选择提示 -->
        <p class="date-tip" v-if="selectedDate && returnDate">
          租期：{{ getDateDiff() }} 天
        </p>
      </div>

      <!-- 押金+价格区 -->
      <div class="clothes-rent-fee">
        <div class="clothes-rent-deposit">
          <span class="fee-label">押金：</span>
          <span class="deposit-amount">¥{{ clothes.deposit}}</span>
        </div>
        <div class="clothes-rent-price">
          <span class="fee-label">总费用：</span>
          <span class="total-amount">¥{{ getTotal() }}</span>
          <span class="fee-desc">(租金+押金)</span>
        </div>
      </div>

      <!-- 数量选择区 -->
      <div class="rent-quantity-container">
        <h3 class="quantity-title">租借数量</h3>
        <div class="rent-quantity">
          <button 
            class="quantity-btn minus-btn" 
            @click="decrementQuantity"
            :disabled="quantity <= 1"
          >-</button>
          <span class="quantity">{{ quantity }}</span>
          <button class="quantity-btn plus-btn" @click="incrementQuantity">+</button>
        </div>
      </div>
      <!-- 订单备注输入框 -->
      <div class="order-remark-container">
        <h3 class="remark-title">订单备注</h3>
        <textarea 
          v-model="orderRemark" 
          placeholder="请输入订单备注" 
          class="remark-input"
          rows="3"
        ></textarea>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="clothes-info-button">
      <button class="add-cart-btn" @click="addToCart">加入购物车</button>
      <button class="buy-now-btn" @click="rentClothes">立即租借</button>
    </div>
  </div>
</template>

<script setup >
import { onMounted, ref, computed } from 'vue'
import axios from 'axios'
import { useRoute } from 'vue-router'

const route = useRoute()
const id = ref() // 商品id
const clothes = ref({}) // 商品信息
const rentdata =ref(1) // 租借天数
const orderId = ref('') // 订单id
const orderRemark = ref('') // 订单备注
const totalPrice =ref() // 总费用

// 尺寸相关
const sizeOptions = ref([])
const selectedSize = ref('S')

// 日期相关
const selectedDate = ref('') // 租借开始日
const returnDate = ref('') // 归还日
const quantity = ref(1) // 租借数量

// 获取今天日期（YYYY-MM-DD），限制日期选择不能早于今天
const getToday = () => {
  return new Date().toISOString().split('T')[0]
}

// 计算租期天数
const getDateDiff = () => {
  if (!selectedDate.value || !returnDate.value) return 0
  const start = new Date(selectedDate.value)
  const end = new Date(returnDate.value)
  const diffTime = end - start
  const rentdata = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1 // 包含首尾日期
  return rentdata
}

// 处理自定义尺寸（去除非字符/数字内容）
const handleCustomSize = () => {
  selectedSize.value = selectedSize.value.replace(/[^a-zA-Z0-9]/g, '')
}

// 数量加减
const incrementQuantity = () => {
  //超库存最大值弹出错误
  // 查找当前尺寸库存
  const selectedSizeStock = sizeOptions.value.find(size => size.size === selectedSize.value)
  // 超库存最大值弹出错误
  if (quantity.value < selectedSizeStock.totalNum) {
    quantity.value++
  }else{
    alert(`当前尺寸库存仅${selectedSizeStock.totalNum}件，无法租借${quantity.value+1}件`)
    return 
  }
 
}
const decrementQuantity = () => {
  if (quantity.value > 1) quantity.value--
}
// 计算总费用
const getTotal = () => {
  return clothes.value.price * getDateDiff() + Number(clothes.value.deposit)
}



import { useLoginStore } from '@/stores/loginStore'
const loginStore = useLoginStore()


// 加载商品信息
onMounted(async () => {
  id.value = route.params.id
  try {
    const response = await axios.get(`/api/clothes/getClothesById/${id.value}`)
    const res = await axios.get(`/api/clothes/getStockById/${id.value}`)
    clothes.value = response.data.data || {} // 从后端获取商品信息
    sizeOptions.value = res.data.data || [] // 从后端获取尺寸库存
    // console.log(clothes.value)
    console.log(sizeOptions.value)
  } catch (err) {
    alert('获取商品信息失败', err)
  }
})

//加入订单
const rentClothes = async () => {
  if (!selectedSize.value) {
    alert('请选择尺寸')
    return
  }
  if (getDateDiff() <= 0) {
    alert('请选择正确的租借时间')
    return
  }
  // 加入订单逻辑 向后端传值
  const order = await axios.post('/api/rentOrder/insertRentOrder',{
    orderNo: orderId.value,
    rentStartTime: selectedDate.value,
    rentEndTime: returnDate.value,
    totalDays: rentdata.value,
    totalPrice: getTotal(),
    deposit: Number(clothes.value.deposit),
    payStatus: 1,
    orderStatus: 1,
    remark: orderRemark.value,
    createTime: new Date().toLocaleString()
  },{
    headers: {
      'Authorization': loginStore.loginToken
    },
  })
  if (order.data.code ==   200) {

    alert('加入订单成功')
  } else {
    console.log(order.data)
    alert('加入订单失败')
  }
}

// }
// 加入购物车
// const addToCart = () => {
//   if (!selectedSize.value) {
//     alert('请选择尺寸')
//     return
//   }
//   if (getDateDiff() <= 0) {
//     alert('请选择正确的租借时间')
//     return
//   }
//   // 加入购物车逻辑 向后端传值
//   const Cart = await axios.post('/api/cart/addShoppingCar'/{
//     clothesId: id.value,
//     size: selectedSize.value,
//     return_price: calculateTotalFee.value,
//     return_date: returnDate.value
//   })
//   if (Cart.data.code === 200) {
//     alert('加入购物车成功')
//   } else {
//     alert('加入购物车失败')
//   }
// }



</script>

<style scoped>
/* 全局容器：横向布局，响应式换行 */
.clothes-info {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fafafa;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 商品图片 */
.clothes-image {
  flex: 0 0 200px;
  height: 200px;
  border-radius: 12px;
  overflow: hidden;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.goods-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}
.goods-img:hover {
  transform: scale(1.05);
}

/* 商品信息主内容区 */
.clothes-info-content {
  flex: 1;
  min-width: 300px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 商品基础信息（名称、描述、价格） */
.clothes-info-content-text {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.goods-name {
  font-size: 22px;
  color: #333;
  font-weight: 600;
  margin: 0;
  line-height: 1.3;
}
.goods-desc {
  font-size: 14px;
  color: #666;
  margin: 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.goods-price {
  font-size: 20px;
  color: #e74c3c;
  font-weight: 600;
  margin: 8px 0 0 0;
}

/* 尺寸选择区样式（优化后） */
.clothes-size-selector {
  padding: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.03);
}
.size-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 12px 0;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}
.size-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background-color: #27ae60;
  border-radius: 2px;
}
.size-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}
.size-radio {
  cursor: pointer;
  position: relative;
  transition: transform 0.2s ease;
}
.size-radio:hover:not(.disabled) {
  transform: translateY(-2px);
}
.native-radio {
  display: none;
}
.radio-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 52px;
  height: 36px;
  border-radius: 8px;
  border: 1px solid #e5e5e5;
  background-color: #f8f8f8;
  color: #333;
  font-size: 14px;
  transition: all 0.2s ease;
}
.native-radio:checked + .radio-btn {
  border-color: #27ae60;
  background-color: #f0f9f4;
  color: #27ae60;
  font-weight: 600;
  box-shadow: 0 0 0 2px rgba(39, 174, 96, 0.15);
}
.native-radio:disabled + .radio-btn {
  border-color: #eee;
  background-color: #fafafa;
  color: #ccc;
  cursor: not-allowed;
}
.stock-tip {
  position: absolute;
  top: -6px;
  right: -6px;
  font-size: 10px;
  color: #fff;
  background-color: #e74c3c;
  padding: 1px 4px;
  border-radius: 4px;
  z-index: 1;
}
/* 自定义尺寸输入框 */
.size-input {
  height: 36px;
  padding: 0 12px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
  outline: none;
  transition: border-color 0.2s ease;
  width: 100px;
}
.size-input:focus {
  border-color: #27ae60;
  box-shadow: 0 0 0 2px rgba(39, 174, 96, 0.1);
}
.size-input::placeholder {
  color: #999;
}

/* 日期选择区样式 */
.clothes-rent-date-selector {
  padding: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.03);
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.date-title {
  font-size: 16px;
  color: #333;
  margin: 0;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}
.date-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background-color: #3498db;
  border-radius: 2px;
}
.date-group {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}
.date-input {
  flex: 1;
  min-width: 140px;
  height: 38px;
  padding: 0 12px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
  outline: none;
  transition: all 0.2s ease;
  background-color: #f8f8f8;
}
.date-input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.1);
  background-color: #fff;
}
.date-gap {
  font-size: 16px;
  color: #999;
  padding: 0 4px;
}
.date-tip {
  font-size: 13px;
  color: #666;
  margin: 0;
  padding-left: 2px;
}

/* 费用展示区（押金+总费用） */
.clothes-rent-fee {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.03);
}
.clothes-rent-deposit, .clothes-rent-price {
  display: flex;
  align-items: center;
  gap: 8px;
}
.fee-label {
  font-size: 14px;
  color: #666;
}
.deposit-amount {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}
.total-amount {
  font-size: 18px;
  color: #e74c3c;
  font-weight: 600;
}
.fee-desc {
  font-size: 12px;
  color: #999;
}

/* 数量选择区样式 */
.rent-quantity-container {
  padding: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.03);
  display: flex;
  align-items: center;
  gap: 16px;
}
.quantity-title {
  font-size: 16px;
  color: #333;
  margin: 0;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}
.quantity-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background-color: #9b59b6;
  border-radius: 2px;
}
.rent-quantity {
  display: flex;
  align-items: center;
  gap: 0;
  height: 36px;
}
.quantity-btn {
  width: 36px;
  height: 100%;
  border: 1px solid #e5e5e5;
  background-color: #f8f8f8;
  color: #333;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 0;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.minus-btn {
  border-radius: 8px 0 0 8px;
  border-right: none;
}
.plus-btn {
  border-radius: 0 8px 8px 0;
  border-left: none;
}
.quantity-btn:hover:not(:disabled) {
  background-color: #eee;
  color: #27ae60;
}
.quantity-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
  background-color: #fafafa;
}
.quantity {
  width: 48px;
  height: 100%;
  border-top: 1px solid #e5e5e5;
  border-bottom: 1px solid #e5e5e5;
  background-color: #fff;
  color: #333;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 底部操作按钮 */
.clothes-info-button {
  display: flex;
  gap: 16px;
  margin-top: 12px;
  width: 100%;
}
.add-cart-btn, .buy-now-btn {
  flex: 1;
  height: 48px;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}
.add-cart-btn {
  background-color: #fff;
  color: #27ae60;
  border: 1px solid #27ae60;
}
.add-cart-btn:hover {
  background-color: #f0f9f4;
  box-shadow: 0 2px 8px rgba(39, 174, 96, 0.1);
}
.buy-now-btn {
  background-color: #27ae60;
  color: #fff;
}
.buy-now-btn:hover {
  background-color: #219653;
  box-shadow: 0 2px 8px rgba(39, 174, 96, 0.2);
}

/* 响应式适配：小屏幕优化 */
@media (max-width: 768px) {
  .clothes-info {
    padding: 16px;
    gap: 16px;
  }
  .clothes-image {
    flex: 0 0 160px;
    height: 160px;
  }
  .goods-name {
    font-size: 20px;
  }
  .goods-price {
    font-size: 18px;
  }
  .clothes-info-button {
    gap: 12px;
  }
  .add-cart-btn, .buy-now-btn {
    height: 44px;
    font-size: 15px;
  }
}

@media (max-width: 480px) {
  .clothes-info {
    flex-direction: column;
    align-items: center;
  }
  .clothes-image {
    width: 100%;
    max-width: 200px;
  }
  .clothes-info-content {
    width: 100%;
    min-width: auto;
  }
  .clothes-info-button {
    flex-direction: column;
  }
}
</style>